package com.mxx.tomcat;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @Auther: Mr. Zeng
 * @Date: 2020/6/28 13:15
 * @Description: 暂无描述
 */
@RestController
public class UrlForwardController implements DomainController {

    @Value("${server.servlet.context-path:''}")
    private String contextPath;


    @GetMapping("/")
    public ModelAndView level0() {
        return redirect("index.html");
    }

    @GetMapping("/*.html")
    public ModelAndView level1(HttpServletRequest request) {
        String uri = request.getRequestURI();
        uri = uri.substring(0, uri.length() - 5);
        return forward(uri);
    }

    @GetMapping("/*/*.html")
    public ModelAndView level2(HttpServletRequest request) {
        String uri = request.getRequestURI();
        uri = uri.substring(0, uri.length() - 5);
        return forward(uri);
    }

    @GetMapping("/*/*/*.html")
    public ModelAndView level3(HttpServletRequest request) {
        String uri = request.getRequestURI();
        uri = uri.substring(0, uri.length() - 5);
        return forward(uri);
    }

    @GetMapping("/*/*/*/*.html")
    public ModelAndView level4(HttpServletRequest request) {
        String uri = request.getRequestURI();
        uri = uri.substring(0, uri.length() - 5);
        return forward(uri);
    }

    public ModelAndView redirect(String viewName) {
        return new ModelAndView("redirect:" + res(viewName));
    }

    public ModelAndView forward(String viewName) {
        return new ModelAndView((res(viewName.replace(contextPath, ""))));
    }

    private String res(String url) {
        if (url.startsWith("/")) {
            res(url.substring(1));
        } else {
            return url;
        }
        return url;
    }

}
